package com.souku.finance.application.ui.more;

import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.manager.RequestManager;
import com.souku.finance.application.R;
import com.souku.finance.application.base.BaseCropPictureActivity;
import com.souku.finance.application.ui.login.LoginActivity;
import com.souku.finance.application.base.BaseActivity;
import com.souku.finance.application.ui.mine.EAccountActivity;
import com.souku.finance.application.utils.Constant;
import com.souku.finance.application.http.UrlConstact;
import com.souku.finance.application.ui.lock.LockActivity;
import com.souku.finance.application.utils.JsonUtil;
import com.souku.finance.application.utils.ParamUtil;
import com.souku.finance.application.utils.ShareUtil;
import com.souku.finance.application.utils.ToastUtil;
import com.souku.finance.application.utils.UploadFile;
import com.souku.finance.application.utils.UploadImageUtil;
import com.souku.finance.application.widget.BackgroundRelativeLayout;
import com.souku.finance.application.widget.ButtonWait;
import com.souku.finance.application.dialog.WaitDialog;
import com.souku.finance.application.http.volley.ReqListener;
import com.souku.finance.application.http.volley.RequestSuccessError;

import java.io.File;
import java.util.HashMap;

/**
 * Created by Android on 2016/12/8.
 */

public class AccountCenterActivity extends BaseCropPictureActivity implements View.OnClickListener {

    protected RelativeLayout topBack;
    protected TextView topTitle;
    protected BackgroundRelativeLayout rlSethead;
    protected BackgroundRelativeLayout rlCard;
    protected BackgroundRelativeLayout rlSetloginpass;
    protected BackgroundRelativeLayout rlSetpaypass;
    protected BackgroundRelativeLayout rlSetgrass;
    protected ButtonWait getout;
    private Uri mUri;
    private WaitDialog waitDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.act_accountcenter);
        initView();
        topTitle.setText("账户中心");
        waitDialog = new WaitDialog(this);
    }

    @Override
    public void internet() {

    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.top_back) {
            finish();
        } else if (view.getId() == R.id.rl_sethead) {
            AlertDialog.Builder dialog = new AlertDialog.Builder(this);
            dialog.setTitle("选择图片").setNegativeButton("相册", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
//                    Intent pickIntent = new Intent(Intent.ACTION_PICK, null);
//                    pickIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
//                    startActivityForResult(pickIntent, UploadImageUtil.REQUEST_IMAGE);
                    pickImage();
                }
            }).setPositiveButton("拍照", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
//                    Intent takeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//                    File file = new File(Environment.getExternalStorageDirectory() + "/Images");
//                    if (!file.exists()) {
//                        file.mkdirs();
//                    }
//                    mUri = Uri.fromFile(
//                            new File(Environment.getExternalStorageDirectory() + "/Images/",
//                                    "cameraImg" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
//                    takeIntent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
//                    takeIntent.putExtra("return-data", true);
//                    startActivityForResult(takeIntent, UploadImageUtil.REQUEST_PHOTO);
                    launchCamera();
                }
            }).create().show();
        } else if (view.getId() == R.id.rl_card) {
//            Intent intent = new Intent(this, BankCardActivity.class);
//            startActivity(intent);
            Intent intent = new Intent();
            String isBind = ShareUtil.getInstance().getString(Constant.IsBind);
            if (isBind.equals("0")) {
                intent.setClass(this, EAccountActivity.class);//去绑定E账号
                startActivity(intent);
            } else {
                intent.setClass(this, BankCard2Activity.class);//去绑定银行卡
                startActivity(intent);
            }

        } else if (view.getId() == R.id.rl_setloginpass) {
            Intent intent = new Intent(this, ResetLoginPassActivity.class);
            startActivity(intent);
        } else if (view.getId() == R.id.rl_setpaypass) {
            if (ShareUtil.getInstance().getBoolean(Constant.IsBind)) {
                Intent intent = new Intent(this, ResetPayPassActivity.class);
                startActivity(intent);
            } else {
                ToastUtil.show("请先绑定银行卡");
            }
        } else if (view.getId() == R.id.rl_setgrass) {
            Intent i4 = new Intent(AccountCenterActivity.this,
                    LockActivity.class);
            i4.putExtra("change", true);
            startActivity(i4);
        } else if (view.getId() == R.id.getout) {
            logout();
        }
    }

    private void initView() {
        topBack = (RelativeLayout) findViewById(R.id.top_back);
        topBack.setOnClickListener(AccountCenterActivity.this);
        topTitle = (TextView) findViewById(R.id.top_title);
        rlSethead = (BackgroundRelativeLayout) findViewById(R.id.rl_sethead);
        rlSethead.setOnClickListener(AccountCenterActivity.this);
        rlCard = (BackgroundRelativeLayout) findViewById(R.id.rl_card);
        rlCard.setOnClickListener(AccountCenterActivity.this);
        rlSetloginpass = (BackgroundRelativeLayout) findViewById(R.id.rl_setloginpass);
        rlSetloginpass.setOnClickListener(AccountCenterActivity.this);
        rlSetpaypass = (BackgroundRelativeLayout) findViewById(R.id.rl_setpaypass);
        rlSetpaypass.setOnClickListener(AccountCenterActivity.this);
        rlSetgrass = (BackgroundRelativeLayout) findViewById(R.id.rl_setgrass);
        rlSetgrass.setOnClickListener(AccountCenterActivity.this);
        getout = (ButtonWait) findViewById(R.id.getout);
        getout.setOnClickListener(AccountCenterActivity.this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

//        File croppedImageFile = new File(getFilesDir(), "avatar.JPEG");
        //判断返回状态，REQUEST_FIX截图完毕

//        if (requestCode == UploadImageUtil.REQUEST_FIX) {
//            MoreFragment.ivHead.setImageURI(mUri);
//            try {
//                AsyncHttpClient client = new AsyncHttpClient();
//                RequestParams params = new RequestParams();
////                params.put("avatar", croppedImageFile, "image/png", "avatar.png");
//                params.put("avatar", croppedImageFile);
//                params.put(Constant.Token, ShareUtil.getInstance().getString(Constant.Token));
//                HashMap<String, String> map = ParamUtil.getParams();
//                map.putAll(ParamUtil.getHeaders());
//                for (String s : map.keySet()) {
//                    params.put(s, map.get(s));
//                }
//                if (!waitDialog.isShowing()) {
//                    waitDialog.show();
//                }
//                client.post(UrlConstact.UPLOAD_AVATAR_IMG, params, new AsyncHttpResponseHandler() {
//                    @Override
//                    public void onSuccess(int i, Header[] headers, byte[] bytes) {
//                        String response = new String(bytes);
//                        String avatar = JsonUtil.getString(JsonUtil.getData(response), "avatar");
//                        //保存头像url到SQL
//                        AvatarUtil.insert(AccountCenterActivity.this, ShareUtil.getInstance().getString(Constant.Mobile), avatar);
//                        ShareUtil.getInstance().putExtra(Constant.AvatarUrl, avatar);
//                        if (waitDialog.isShowing()) {
//                            waitDialog.setfinish("上传成功");
//                        }
//                    }
//
//                    @Override
//                    public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
//                        if (waitDialog.isShowing()) {
//                            waitDialog.setfinish("上传失败");
//                        }
//                    }
//                });
//            } catch (FileNotFoundException e) {
//                e.printStackTrace();
//            }

//            UploadFile.uploadFile2(this, croppedImageFile.getAbsolutePath());

//          content://media/external/images/media/395661

//          file:///data/data/com.lzg.xiaoke/files/avatar.JPEG

        //选择图片完毕
//        } else if (requestCode == UploadImageUtil.REQUEST_IMAGE) {
//            if (data == null) return;
//            if (data.getData() != null || data.getExtras() != null) { //防止没有返回结果
//                Uri uri = data.getData();
//                Uri croppedImage = Uri.fromFile(croppedImageFile);
//                CropImageIntentBuilder cropImage = new CropImageIntentBuilder(200, 200, croppedImage);
//                cropImage.setOutlineColor(0xFF03A9F4);
//                cropImage.setSourceImage(uri);
//                startActivityForResult(cropImage.getIntent(this), UploadImageUtil.REQUEST_FIX);
//            }
//            //拍照完毕
//        } else if (requestCode == UploadImageUtil.REQUEST_PHOTO) {
//            Uri croppedImage = Uri.fromFile(croppedImageFile);
//            CropImageIntentBuilder cropImage = new CropImageIntentBuilder(200, 200, croppedImage);
//            cropImage.setOutlineColor(0xFF03A9F4);
//            cropImage.setSourceImage(mUri);
//            startActivityForResult(cropImage.getIntent(this), UploadImageUtil.REQUEST_FIX);
//        }

    }

    @Override
    protected void onActivitySingleImage(String path) {
        super.onActivitySingleImage(path);
        if (!TextUtils.isEmpty(path)) {
            UploadFile.uploadFile2(this, path);
        }
    }

    private void logout() {
        HashMap<String, String> map = ParamUtil.getParams();
        RequestManager.getInstance().post(UrlConstact.LOGOUT, ParamUtil.getSing(map), new ReqListener(this, new RequestSuccessError() {
            @Override
            public void onRequest() {
                getout.setEnabled(false);
            }

            @Override
            public void onSuccess(String response) {
                getout.setEnabled(true);
                if (JsonUtil.getCode(response) == 1) {
                    ShareUtil.getInstance().getOut();
                    Intent intent = new Intent(AccountCenterActivity.this, LoginActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    ToastUtil.show(JsonUtil.getMessage(response));
                }
            }

            @Override
            public void onError(String errorMsg) {
                getout.setEnabled(true);
                ToastUtil.show("请检查网络");
            }
        }), ParamUtil.getHeaders());
    }

    public static String getRealFilePath(final Context context, final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    public void getFileUri(String picPath, Uri mImageUri) {
        Uri mUri = Uri.parse("content://media/external/images/media");
        Cursor cursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null
                , null, MediaStore.Images.Media.DEFAULT_SORT_ORDER);
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            String data = cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DATA));
            if (picPath.equals(data)) {
                int ringtoneID = cursor.getInt(cursor
                        .getColumnIndex(MediaStore.MediaColumns._ID));
                mImageUri = Uri.withAppendedPath(mUri, "" + ringtoneID);
                break;
            }
            cursor.moveToNext();
        }
    }

    //---------------------------------------------------------------------------------------------

    /**
     * 适配api11-api18,根据uri获取图片的绝对路径
     */
//    private static String getRealPathFromUri_Api11To18(Context context, Uri uri) {
//        String filePath = null;
//        String[] projection = {MediaStore.Images.Media.DATA};
//        CursorLoader loader = new CursorLoader(context, uri, projection, null, null, null);
//        Cursor cursor = loader.loadInBackground();
//
//        if (cursor != null) {
//            cursor.moveToFirst();
//            filePath = cursor.getString(cursor.getColumnIndex(projection[0]));
//            cursor.close();
//        }
//        return filePath;
//    }

    /**
     * 适配api19以上,根据uri获取图片的绝对路径
     */
//    @TargetApi(Build.VERSION_CODES.KITKAT)
//    private static String getRealPathFromUri_AboveApi19(Context context, Uri uri) {
//        String filePath = null;
//        String wholeID = DocumentsContract.getDocumentId(uri);
//
//        // 使用':'分割
//        String id = wholeID.split(":")[1];
//
//        String[] projection = {MediaStore.Images.Media.DATA};
//        String selection = MediaStore.Images.Media._ID + "=?";
//        String[] selectionArgs = {id};
//
//        Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,//
//                projection, selection, selectionArgs, null);
//        int columnIndex = cursor.getColumnIndex(projection[0]);
//        if (cursor.moveToFirst()) filePath = cursor.getString(columnIndex);
//        cursor.close();
//        return filePath;
//    }

    /**
     * 适配api11以下(不包括api11),根据uri获取图片的绝对路径
     */
//    private static String getRealPathFromUri_BelowApi11(Context context, Uri uri) {
//        String filePath = null;
//        String[] projection = {MediaStore.Images.Media.DATA};
//        Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);
//        if (cursor != null) {
//            cursor.moveToFirst();
//            filePath = cursor.getString(cursor.getColumnIndex(projection[0]));
//            cursor.close();
//        }
//        return filePath;
//    }

}
